<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        ref="queryForm"
        @submit.native.prevent
        :inline="true"
        v-show="showSearch"
        label-width="80px"
      >
        <el-form-item label="数据库组名" prop="groupName">
          <common-input
            v-model="queryParams.groupName"
            clearable
            @keyup.enter.native="handleQuery"
            @enter="handleQuery"
          />
        </el-form-item>
        <common-dept
          ref="commonDept"
          :currentParent="currentParent"
          @getDeptId="getDeptId"
          @getDeptList="getDeptList"
          @getLoading="getLoading"
        ></common-dept>
      </el-form>
    </common-search>

    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['datascan:dbgroup:add']"
        >新增
        </el-button>
        <el-button
          plain
          type="danger"
          icon="el-icon-delete"
          :disabled="!showBatch"
          @click="handleDelete()"
          v-hasPermi="['datascan:dbgroup:remove']"
        >批量删除
        </el-button>
      </el-col>
    </el-row>

    <common-table
      v-loading="loading"
      slot="content"
      :data="list"
      style="height: 100%; margin: 0 !important"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="数据库组名" prop="groupName"/>
      <el-table-column label="组织" align="left" prop="deptName" />
      <el-table-column label="备注" prop="remark" show-overflow-tooltip/>
      <!--      <el-table-column label="数据库组管理员" align="left" prop="adminUserCode" width="120px"/>-->
      <!--<el-table-column label="状态" align="left" prop="status" width="100px">
        <template slot-scope="scope">
          <el-tag  type="success" effect="plain" v-if="scope.row.status === 0">启用</el-tag>
          <el-tag  type="danger" effect="plain" v-else>停用</el-tag>
        </template>
      </el-table-column>-->
      <el-table-column
        label="操作"
        align="left"
        width="90"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!--          <el-button type="text" @click="showInfo(scope.row.id)" v-hasPermi="['system:group:info']">详情
          </el-button>-->
          <el-button
            type="text"
            @click="handleEdit(scope.row.id)"
            v-hasPermi="['datascan:dbgroup:edit']"
          >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['datascan:dbgroup:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>
    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handleList"
    />

    <!-- 添加或编辑数据库组对话框 -->
    <common-edit-dialog
      :title="isEdit ? '编辑数据库组' : '新增数据库组'"
      :visible.sync="open"
      @cancel="cancel"
      @submit="submitForm"
      :buttonLoading="buttonLoading"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px" @submit.native.prevent>
        <el-row :gutter="18">
          <el-col :span="24">
            <el-form-item label="数据库组名" prop="groupName">
              <common-input v-model="form.groupName" placeholder="请输入" :maxlength="16"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <common-add-dept
              ref="commonAddDept"
              :deptListParams="deptListParams"
              @getCheckedDeptId="getCheckedDeptId"
              :deptId="form.deptId"
            ></common-add-dept>
          </el-col>
          <!--<el-form-item label="数据库组管理员" prop="adminUserCode">
            <el-select v-model="form.adminUserCode" placeholder="请选择数据库组管理员" style="width: 100%">
              <el-option
                v-for="item in adminUserList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>-->
          <!--        <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                      <el-radio :label="0">启用</el-radio>
                      <el-radio :label="1">停用</el-radio>
                    </el-radio-group>
                  </el-form-item>-->
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <common-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>

    <common-info-dialog :visible.sync="infoShow" @cancel="hiddenInfo">
      <common-info-table>
        <common-info-table-cell label="数据库组名">{{
          info.groupName
          }}
        </common-info-table-cell>
        <common-info-table-cell label="数据库">{{
          info.dbNames
          }}
        </common-info-table-cell>
        <common-info-table-cell label="数据库组描述">{{
          info.remark
          }}
        </common-info-table-cell>
      </common-info-table>
    </common-info-dialog>
  </common-list>
</template>

<script>
  import {
    queryGroupListByPage,
    addGroup,
    updateGroup,
    deleteGroup,
    queryGroupInfo,
    queryUserList,
    deleteGroupForCheck
  } from '@/api/datascan/dbgroup/group'
  import BaseIndex from '@/mixins/BaseIndex'
  import CommonList from '@/template/CommonList'
  import BaseList from '@/mixins/BaseList'
  import { getSingleArray, getFullDept } from "@/utils/util"

  const form = {
    id: null,
    groupName: null, // 组名称
    adminUserCode: null, // 管理员编码
    dbIds: null, // 关联的数据库id
    status: 0, // 状态:0:启用 1:停用
    remark: null, // 描述
    deptId: null
  }

  export default {
    name: 'Group',
    components: {
      CommonList
    },
    mixins: [BaseIndex, BaseList],
    created() {
      this.getUserList()
    },
    data() {
      return {
        key: 'id',
        isEdit: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          groupName: null,
          deptIds: null
        },

        // 表单参数
        form: {
          ...form
        },
        // 表单校验
        rules: {
          groupName: [
            { required: true, message: '请输入数据库组名', trigger: 'blur' }
          ],
          // deptId: [{ required: true, message: '请选择组织', trigger: 'blur' }],
          /*    adminUserCode: [
                {required: true, message: "请选择数据库组管理员", trigger: "blur"},
              ]*/
        },
        infoShow: false,
        info: {
          groupName: null, // 组名称
          dbNames: null, // 关联的数据库id
          remark: null // 描述
        },
        dbInfoList: [], // 数据库列表
        adminUserList: [],// 管理员列表
        currentParent: 4,
        singleDeptList: [],
        deptListParams: []
      }
    },
    methods: {
      getLoading(){
        this.loading = true;
      },
      getCheckedDeptId(val){
        this.form.deptId = val;
      },
      getDeptList(list) {
        this.deptListParams = list;
        this.singleDeptList = getSingleArray(list);
        this.handleList();
      },
      getDeptId(val) {
        this.queryParams.deptIds = val;
      },
      getDeptName(val) {
        let dept = this.singleDeptList.find((item) => item.id === val.toString());
        if (dept) return getFullDept(dept.fulllabel);
      },

      handleList(){
        this.loading = true
        this.getList().then(({ list, total }) => {
          this.list = list
          this.total = total
        }).finally(() => {
          this.loading = false
        })
      },

      /** 查询数据库信息列表 */
      getList() {
        return new Promise((resolve, reject) => {
          queryGroupListByPage(this.queryParams)
            .then((res) => {
              if (res && res.code === 200 && res.data) {
                resolve({
                  total: res.data.totalCount,
                  list: res.data.dataList.reduce((r, c) => {
                    c.deptName = this.getDeptName(c.deptId || "")
                    r.push(c)
                    return r
                  }, [])
                })
              } else {
                resolve({
                  total: 0,
                  list: []
                })
                this.handleListTips(res)
              }
            })
        })
      },
      /**
       * 根据id获取详情方法
       * @param id
       * @returns {Promise<unknown>}
       */
      getInfo(id) {
        let group = this.list.find((g) => g.id === id)
        let dbIds = group ? group.dbIdList : []
        let dbNames = this.dbInfoList
          .reduce((r, c) => {
            let includes = dbIds.includes(c.value)
            if (includes) r.push(c.label)
            return r
          }, [])
          .join(',')
        return new Promise((resolve, reject) => {
          queryGroupInfo({ id: id })
            .then((res) => {
              if (res && res.code === 200 && res.data) {
                resolve({
                  ...res.data,
                  dbIds,
                  dbNames
                })
              } else {
                this.$GlobalErrorConfirm('数据加载失败', res.msg)
              }
            })
        })
      },
      update(form) {
        return new Promise((resolve, reject) => {
          this.buttonLoading = true; 
          updateGroup(form)
            .then((res) => {
              resolve(res)
              if (res && res.code === 200) {
                this.isEdit = false
              } else {
                this.$GlobalErrorConfirm('编辑失败', res.msg)
              }
            })
            .finally(() => {
              this.buttonLoading = false
            })
        })
      },
      add(form) {
        return new Promise((resolve, reject) => {
          this.buttonLoading = true; 
          addGroup(form)
            .then((res) => {
              if (res && res.code === 200) {
                this.isEdit = true
                resolve(res)
              } else {
                this.$GlobalErrorConfirm('新增失败', res.msg)
              }
            })
            .finally(() => {
              this.buttonLoading = false
            })
        })
      },
      del(id) {
        return new Promise((resolve, reject) => {
          deleteGroup({ ids: id })
            .then((res) => {
              if (res && res.code === 200) {
                resolve(res)
              } else {
                this.$GlobalErrorConfirm('删除失败', res.msg)
              }
            })
        })
      },
      showInfo(id) {
        this.infoShow = true
        this.getInfo(id)
          .then((res) => {
            this.info.remark = res.remark
            this.info.groupName = res.groupName
            this.info.dbNames = res.dbNames
          })
      },
      hiddenInfo() {
        this.infoShow = false
      },
      getUserList() {
        queryUserList({})
          .then((res) => {
            if (res && res.code === 200) {
              if (res.data.dataList) {
                this.adminUserList = res.data.dataList.reduce((r, c) => {
                  r.push({
                    label: c.userName,
                    value: c.userId
                  })
                  return r
                }, [])
              } else {
                this.adminUserList = []
              }
            }
          })
      },
      resetQuery(){
        this.queryParams = this.$options.data().queryParams;
        this.$refs.commonDept.clearDept();
      },

      // ——————————————————————————删除————————————————————————
      deleteData(row) {
        let id = row?.id || this.ids.join(',')
        this.$GlobalDeleteConfirm().then(() => {
          this.del(id).then(res => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage('删除成功')
              // this.queryParams.pageNum=1
              if (this.queryParams.pageNum>1 && id.toString().split(',').length===this.list.length){
                this.queryParams.pageNum-=1
              }
              this.handleList()
            } else {
              this.$GlobalErrorConfirm('删除失败',res.msg)
            }
          })
        }).catch(()=>{});
      },

      /**  删除前校验 */
      beforeDeleteForCheck(ids) {
        return new Promise((resolve, reject) => {
          deleteGroupForCheck({ ids: ids }).then(res => {
            if(res && res.code === 200) {
              resolve(res)
            } else {
              reject(res)
            }
          }).catch(err => {
            reject(err)
          })
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .info-table {
    .info-row {
      height: 39px;
      display: flex;
      border-top: 1px solid rgb(232, 232, 232);

      &:last-child {
        border-bottom: 1px solid rgb(232, 232, 232);
      }

      .info-label {
        width: 160px;
        height: 100%;
        line-height: 39px;
        background-color: #f5f5f5;
        text-align: right;
        padding-right: 8px;
        box-sizing: border-box;
      }

      .info-value {
        height: 100%;
        line-height: 39px;
        padding-left: 8px;
        box-sizing: border-box;
      }
    }
  }
</style>
